/**
 * @file 通用数据
 */

import Fingerprint2 from 'fingerprintjs2';
import { i18n } from '@/locales/';
import router from '@/router/';
import cookie from '@/utils/cookie';
import site from '@/config/site';
import types from '../types';

const state = {
    /**
     * 当前主题名称
     *
     * @type {string}
     */
    theme: localStorage.getItem('theme') || site.theme,

    /**
     * 浏览器指纹
     *
     * @type {string}
     */
    fingerprint: '',
};

const getters = {
};

const mutations = {
    // 设置主题
    [types.SET_THEME](state, theme) {
        state.theme = theme;
    },

    // 设置浏览器指纹
    [types.SET_FINGERPRINT_STR](state, str) {
        state.fingerprint = str;
    },
};

const actions = {
    // 生成浏览器指纹
    async [types.BUILD_FINGERPRINT_STR]({ commit }) {
        await Fingerprint2.getPromise().then((result) => {
            const res = result.map(component => component.value);
            const str = Fingerprint2.x64hash128(res.join(''), 31);
            commit(types.SET_FINGERPRINT_STR, str);
        });
    },

    /**
     * 设置语言，只需要一个方法即可实现写入 cookie 、替换链接、更新 state
     *
     * @param {Object} context Store 对象
     * @param {(string|Object)} lang 需要设置的语言，或者配置对象
     * @example
     *  1. 直接使用字符串设置语言，默认链接自动跳转
     *  this.$store.dispatch(types.SET_LANG, 'zh-cn');
     *  2. 设置不跳转链接链接
     *  this.$store.dispatch(types.SET_LANG, {
     *      lang: 'zh-cn',
     *      replace: false,
     *  });
     */
    [types.SET_LANG](context, lang) {
        let options;

        if (typeof lang === 'string') {
            options = {
                lang,
                // 是否替换跳转
                replace: true,
            };
        } else {
            options = {
                ...{
                    replace: true,
                },
                ...lang,
            };
        }

        /**
         * 语言设置 cookie
         * TODO: 有待跟产品确认
         */
        cookie.set('lang', options.lang);

        // 跳转
        if (options.replace) {
            cookie.remove('lang');
            cookie.set('lang', options.lang);
            window.location.href = router.currentRoute.value.fullPath.replace(`/${i18n.locale}`, `/${options.lang}`);
        } else {
            // 设置语言包
            i18n.locale = options.lang;
        }
    },

    [types.SET_THEME]({ commit }, theme) {
        /**
         * 主题 cookie
         * TODO: 有待跟产品确认
         */
        localStorage.setItem('theme', theme);
        commit(types.SET_THEME, theme);
    },
};

export default {
    state,
    getters,
    mutations,
    actions,
};
